<template>
  <div class="product-form-modal" v-if="visible">
    <div class="modal-backdrop" @click="closeModal"></div>

    <div class="modal-container">
      <div class="modal-header">
        <h2 class="modal-title">{{ isEdit ? '编辑产品' : '添加产品' }}</h2>
        <button class="close-btn" @click="closeModal">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <div class="modal-body">
        <form @submit.prevent="submitForm" class="product-form">
          <!-- 商户Id -->
          <div class="form-group" v-if="!formData.shopId">
            <label for="product-name" class="required">商户id</label>

            <input type="text" id="product-name" v-model="formData.shopId" :class="{ error: errors.name }"
              placeholder="请输入商户id" />

            <span class="error-message" v-if="errors.name">{{ errors.name }}</span>
          </div>

          <!-- 产品名称 -->
          <div class="form-group">
            <label for="product-name" class="required">产品名称</label>
            <input type="text" id="product-name" v-model="formData.goods_name" :class="{ error: errors.name }"
              placeholder="请输入产品名称" />
            <span class="error-message" v-if="errors.name">{{ errors.name }}</span>
          </div>

          <!-- 产品图片 -->
          <div class="form-group">
            <label for="product-image">产品图片</label>

            <Upload v-model="formData.productImg" />
          </div>

          <!-- 产品描述 -->
          <div class="form-group">
            <label for="product-description">产品描述</label>
            <textarea id="product-description" v-model="formData.describe" placeholder="请输入产品描述" rows="4"></textarea>
          </div>

          <!-- 产品分类 -->
          <div class="form-group">
            <label for="product-category">产品分类</label>
            <Select v-model="formData.goods_type_id" mode="api" labelKey="title" valueKey="id"
              apiUrl="api/admin/shopLabelAddAndEdit" />
          </div>

          <!-- 价格信息 -->
          <div class="form-section">
            <!-- <h3 class="section-title">价格信息</h3> -->

            <!-- 原价 -->
            <!-- <div class="form-group">
              <label for="product-original-price" class="required">原价</label>
              <div class="price-input">
                <span class="currency-symbol">¥</span>
                <input
                  type="number"
                  id="product-original-price"
                  v-model="formData.originalPrice"
                  :class="{ error: errors.originalPrice }"
                  placeholder="0.00"
                  min="0"
                  step="0.01"
                />
              </div>
              <span class="error-message" v-if="errors.originalPrice">{{
                errors.originalPrice
              }}</span>
            </div> -->

            <!-- 折扣价 -->
            <!-- <div class="form-group">
              <label for="product-discount-price">折扣价 <span class="optional">(可选)</span></label
              >
              <div class="price-input">
                <span class="currency-symbol">¥</span>
                <input
                  type="number"
                  id="product-discount-price"
                  v-model="formData.discount_money"
                  :class="{ error: errors.discountPrice }"
                  placeholder="0.00"
                  min="0"
                  step="0.01"
                />
              </div>

              <span class="error-message" v-if="errors.discountPrice">{{ errors.discountPrice }}</span>

              <span class="hint-message" v-else>如不设置折扣价，则以原价销售</span>
            </div> -->
          </div>

          <!-- 库存信息 -->
          <div class="form-section">
            <h3 class="section-title">库存信息</h3>

            <!-- 库存数量 -->
            <!-- <div class="form-group">
              <label for="product-stock">库存数量</label>
              <input
                type="number"
                id="product-stock"
                v-model="formData.stock"
                placeholder="请输入库存数量"
                min="0"
                step="1"
              />
            </div> -->

            <!-- 产品状态 -->
            <div class="form-group">
              <label for="product-status">产品状态</label>
              <select id="product-status" v-model="formData.status">
                <option value="1">上架</option>
                <option value="0">下架</option>
              </select>
            </div>
          </div>
        </form>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn-cancel" @click="closeModal">取消</button>
        <button type="button" class="btn-submit" @click="submitForm">保存</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'
import Select from '@/components/admin/Select.vue'
import Upload from '@/components/Upload.vue'


// 定义Props和Emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  productData: {
    type: Object as () => {
      id?: string
      merchantId?: string
      name?: string
      image?: string
      description?: string
      originalPrice?: number
      discountPrice?: number | null
      category?: string
      status?: 'active' | 'inactive'
      stock?: number
      [key: string]: any
    },
    default: () => ({}),
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:visible', 'submit'])

// 表单数据
const formData = ref({
  id: '',
  goods_name: '',
  goods_img: '',
  goods_money: '',
  head_img: [''],
  describe: '',
  goods_type_id: '',
  shopId: '',
  status: ''
})

// 表单错误信息
const errors = ref({
  name: '',
  originalPrice: '',
  discountPrice: '',
})

// 文件上传相关
const fileInput = ref<HTMLInputElement | null>(null)
const previewImage = ref('')

// 监听productData变化，更新表单数据
watch(
  () => props.productData,
  (newVal) => {
    console.log(66666666, newVal.merchantId)

    if (newVal && Object.keys(newVal).length > 0) {
      Object.assign(formData.value, newVal)
    } else {
      // 重置表单
      resetForm()
    }
  },
  { immediate: true, deep: true },
)

// 重置表单
function resetForm() {
  formData.value = {
    id: '',
    goods_name: '',
    product: '',
    head_img: [''],
    describe: '',
    goods_type_id: '',
    shopId: ''
  }
  errors.value = { name: '', originalPrice: '', discountPrice: '' }
  previewImage.value = ''
}

// 触发文件选择
function triggerFileInput() {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 处理文件选择
function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    const file = target.files[0]
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target?.result) {
        previewImage.value = e.target.result as string
        // 在实际项目中，这里应该调用上传API
        // formData.value.image = 上传成功后的URL
      }
    }
    reader.readAsDataURL(file)
  }
}

// 移除图片
function removeImage() {
  formData.value.image = ''
  previewImage.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 验证表单
function validateForm() {
  let isValid = true

  // 重置错误信息
  errors.value = { name: '', originalPrice: '', discountPrice: '' }

  // 验证产品名称
  // if (!formData.value.name.trim()) {
  //   errors.value.name = '产品名称不能为空'
  //   isValid = false
  // }

  // 验证原价
  if (formData.value.originalPrice <= 0) {
    errors.value.originalPrice = '原价必须大于0'
    isValid = false
  }

  // 验证折扣价
  // if (formData.value.discountPrice !== null) {
  //   if (formData.value.discountPrice <= 0) {
  //     errors.value.discountPrice = '折扣价必须大于0'
  //     isValid = false
  //   } else if (formData.value.discountPrice >= formData.value.originalPrice) {
  //     errors.value.discountPrice = '折扣价必须小于原价'
  //     isValid = false
  //   }
  // }

  return isValid
}

// 提交表单
function submitForm() {
  //  添加true不验证表单
  if (validateForm() || true) {
    // 在实际项目中，这里会调用API保存数据
    const submitData = {
      ...formData.value,
      head_img: [formData.value.productImg],
      // 如果有预览图但没有保存的image URL，使用预览图
      image: formData.value.image || previewImage.value,
    }

    emit('submit', submitData)

    closeModal()
  }
}

// 关闭模态框
function closeModal() {
  emit('update:visible', false)
}
</script>

<style lang="scss" scoped>
@use 'sass:color'; // 注意必须引入
@import '@/assets/styles/variables.scss';
@import '@/assets/styles/mixins.scss';


.product-form-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: $z-index-modal;
}

.modal-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba($black, 0.5);
  z-index: $z-index-modal-backdrop;
}

.modal-container {
  position: relative;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  background-color: $white;
  border-radius: $border-radius-lg;
  box-shadow: $shadow-xl;
  z-index: $z-index-modal;
  display: flex;
  flex-direction: column;
  animation: modalFadeIn 0.3s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-md $spacing-lg;
  border-bottom: 1px solid $gray-200;

  .modal-title {
    margin: 0;
    font-size: $font-size-xl;
    font-weight: $font-weight-bold;
    color: $text-primary;
  }

  .close-btn {
    background: transparent;
    border: none;
    font-size: $font-size-lg;
    color: $gray-500;
    cursor: pointer;
    padding: $spacing-xs;
    border-radius: $border-radius-full;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all $transition-base;

    &:hover {
      background-color: $gray-100;
      color: $gray-700;
    }
  }
}

.modal-body {
  padding: $spacing-lg;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: $spacing-md $spacing-lg;
  display: flex;
  justify-content: flex-end;
  gap: $spacing-md;
  border-top: 1px solid $gray-200;
}

.product-form {
  display: flex;
  flex-direction: column;
  gap: $spacing-md;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: $spacing-xs;

  label {
    font-size: $font-size-sm;
    font-weight: $font-weight-medium;
    color: $text-secondary;

    &.required::after {
      content: '*';
      color: $danger;
      margin-left: 4px;
    }

    .optional {
      color: $gray-500;
      font-weight: normal;
      font-size: $font-size-xs;
    }
  }

  input,
  select,
  textarea {
    padding: $spacing-sm;
    border: 1px solid $gray-300;
    border-radius: $border-radius-md;
    font-size: $font-size-md;
    color: $text-primary;
    outline: none;
    transition: border-color $transition-base;

    &:focus {
      border-color: $primary;
      box-shadow: 0 0 0 2px rgba($primary, 0.1);
    }

    &.error {
      border-color: $danger;
    }
  }

  textarea {
    resize: vertical;
    min-height: 100px;
  }

  .error-message {
    font-size: $font-size-xs;
    color: $danger;
  }

  .hint-message {
    font-size: $font-size-xs;
    color: $gray-500;
  }

  .price-input {
    position: relative;

    .currency-symbol {
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      color: $text-secondary;
    }

    input {
      padding-left: 25px;
    }
  }
}

.form-section {
  margin-top: $spacing-lg;
  padding-top: $spacing-md;
  border-top: 1px solid $gray-200;

  .section-title {
    margin: 0 0 $spacing-md;
    font-size: $font-size-lg;
    font-weight: $font-weight-semibold;
    color: $text-primary;
  }
}

.image-upload {
  .preview-area {
    position: relative;
    width: 200px;
    height: 150px;
    border-radius: $border-radius-md;
    overflow: hidden;
    border: 1px solid $gray-300;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .remove-btn {
      position: absolute;
      bottom: $spacing-xs;
      right: $spacing-xs;
      width: 28px;
      height: 28px;
      border-radius: $border-radius-full;
      background-color: rgba($black, 0.7);
      color: $white;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: background-color $transition-base;

      &:hover {
        background-color: rgba($danger, 0.8);
      }
    }
  }

  .upload-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2px dashed $gray-300;
    border-radius: $border-radius-md;
    padding: $spacing-lg;
    cursor: pointer;
    transition: all $transition-base;

    i {
      font-size: $font-size-2xl;
      color: $gray-400;
      margin-bottom: $spacing-sm;
    }

    span {
      color: $text-secondary;
      font-size: $font-size-sm;
    }

    .upload-hint {
      color: $text-tertiary;
      font-size: $font-size-xs;
      margin-top: $spacing-xs;
    }

    &:hover {
      border-color: $primary;
      background-color: rgba($primary, 0.05);

      i,
      span {
        color: $primary;
      }
    }
  }
}

.btn-cancel {
  padding: $spacing-xs $spacing-lg;
  border: 1px solid $gray-300;
  border-radius: $border-radius-md;
  background-color: $white;
  color: $text-secondary;
  font-size: $font-size-sm;
  font-weight: $font-weight-medium;
  cursor: pointer;
  transition: all $transition-base;

  &:hover {
    background-color: $gray-100;
    border-color: $gray-400;
  }
}

.btn-submit {
  padding: $spacing-xs $spacing-lg;
  border: none;
  border-radius: $border-radius-md;
  background-color: $primary;
  color: $white;
  font-size: $font-size-sm;
  font-weight: $font-weight-medium;
  cursor: pointer;
  transition: all $transition-base;

  &:hover {
    //background-color: darken($primary, 5%);
    background-color: color.adjust($primary, $lightness: -5%);

  }
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式调整
@media (max-width: $breakpoint-md) {
  .modal-container {
    width: 95%;
    max-height: 95vh;
  }

  .form-section {
    margin-top: $spacing-md;
    padding-top: $spacing-sm;
  }
}
</style>
